package com.mantru.iotpot.Cook;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.DateClass.box_value;
import com.mantru.iotpot.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ThrowVegetablesActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textView1, textView2, textView3, textView4; // 用户选择的投菜方式文本
    private RelativeLayout choiceBox1, choiceBox2, choiceBox3, choiceBox4; // 选择框
    private int box1_value = 0, box2_value = 0, box3_value = 0, box4_value = 0;
    private ApplicationClass ac;
    private List<box_value> boxValues = new ArrayList<>();
    private AlertDialog dialog; // 定义为类的成员变量
    private TextView text1,text2,text3,text4;//dialog中的文本
    private ImageView imageView1,imageView2,imageView3,imageView4;
    private View xian1,xian2,xian3,xian4;
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_throw_vegetables);
        Intent intent = getIntent();
        type = intent.getIntExtra("type",-1);
        ac = (ApplicationClass) getApplication(); // 初始化 ApplicationClass
        initialization(); // 初始化控件
        getJson(); // 解析json数据
        InitializationText();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.throw_vegetables_back) {
            Log.d("ThrowVegetables", "返回");
            ac.SaveSQLData_Handing_Config_Box(box1_value, box2_value, box3_value, box4_value,type);
            Log.d("ThrowVegetables", "box1_value: " + box1_value
                    + " box2_value: " + box2_value + " box3_value: " + box3_value + " box4_value: " + box4_value);
            finish();
        }
    }

    // 用于初始化控件的方法
    public void initialization() {
        textView1 = findViewById(R.id.throw_vegetables_text1);
        textView2 = findViewById(R.id.throw_vegetables_text2);
        textView3 = findViewById(R.id.throw_vegetables_text3);
        textView4 = findViewById(R.id.throw_vegetables_text4);
        choiceBox1 = findViewById(R.id.spinner_demo1);
        choiceBox2 = findViewById(R.id.spinner_demo2);
        choiceBox3 = findViewById(R.id.spinner_demo3);
        choiceBox4 = findViewById(R.id.spinner_demo4);
        findViewById(R.id.throw_vegetables_back).setOnClickListener(this);
        choiceBox1.setOnClickListener(v -> showThrowVegetablesDialog(1));
        choiceBox2.setOnClickListener(v -> showThrowVegetablesDialog(2));
        choiceBox3.setOnClickListener(v -> showThrowVegetablesDialog(3));
        choiceBox4.setOnClickListener(v -> showThrowVegetablesDialog(4));
    }

    // 创建并显示对话框的方法
    private void showThrowVegetablesDialog(int box) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        // 使用布局 inflater 加载对话框布局
        View dialogView = getLayoutInflater().inflate(R.layout.throw_vegetables_dialog_view, null);
        // 创建 AlertDialog.Builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);
        // 创建 AlertDialog
        dialog = builder.create(); // 将 dialog 设置为类的成员变量
        text1 = dialogView.findViewById(R.id.throw_vegetables_dialog_text1);
        text2 = dialogView.findViewById(R.id.throw_vegetables_dialog_text2);
        text3 = dialogView.findViewById(R.id.throw_vegetables_dialog_text3);
        text4 = dialogView.findViewById(R.id.throw_vegetables_dialog_text4);
        imageView1 = dialogView.findViewById(R.id.dialog_img1);
        imageView2 = dialogView.findViewById(R.id.dialog_img2);
        imageView3 = dialogView.findViewById(R.id.dialog_img3);
        imageView4 = dialogView.findViewById(R.id.dialog_img4);
        xian1 = dialogView.findViewById(R.id.dialog_xian1);
        xian2 = dialogView.findViewById(R.id.dialog_xian2);
        xian3 = dialogView.findViewById(R.id.dialog_xian3);
        xian4 = dialogView.findViewById(R.id.dialog_xian4);
        // 为对话框中的文本设置点击事件
        dialogView.findViewById(R.id.dialog_box1).setOnClickListener(v -> textClickListener(box, 1));
        dialogView.findViewById(R.id.dialog_box2).setOnClickListener(v -> textClickListener(box, 2));
        dialogView.findViewById(R.id.dialog_box3).setOnClickListener(v -> textClickListener(box, 3));
        dialogView.findViewById(R.id.dialog_box4).setOnClickListener(v -> textClickListener(box, 4));

        setSelect(box);//将所选的投菜方式标记出来
        // 显示对话框
        dialog.show();
        // 设置对话框背景透明
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
        // 设置对话框的大小(需要在对话框显示之后设置对话框的大小才有用)
        int screenWidth = getResources().getDisplayMetrics().widthPixels; // 获取屏幕宽度
        if (dialog.getWindow() != null) { // 设置对话框宽度为屏幕宽度的80%
            dialog.getWindow().setLayout(
                    (int) (screenWidth * 0.9), // 宽度为屏幕宽度的80%
                    ViewGroup.LayoutParams.WRAP_CONTENT  // 高度包裹内容
            );
        }
    }

    // 获取json数据
    private void getJson() {
        String json_data = ac.GetSQLData_Handing_Config_Box(type);
        Log.d("ThrowVegetables", "json_data: " + json_data);
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            boolean success = jsonObject.getBoolean("success");
            if (success) {
                JSONArray dataArray = jsonObject.getJSONArray("data");  // 获取 data 数组
                for (int i = 0; i < dataArray.length(); i++) {  // 遍历数组
                    JSONObject dataObject = dataArray.getJSONObject(i);  // 获取数组中的每个对象
                    String config_id = dataObject.getString("config_id");
                    String box1 = dataObject.getString("box1_value");
                    String box2 = dataObject.getString("box2_value");
                    String box3 = dataObject.getString("box3_value");
                    String box4 = dataObject.getString("box4_value");
                    boxValues.add(new box_value(config_id, box1, box2, box3, box4));
                    Log.d("ThrowVegetables", "config_id: " + config_id + " box1_value: " + box1
                            + " box2_value: " + box2 + " box3_value: " + box3 + " box4_value: " + box4);
                    box1_value = Integer.valueOf(box1);
                    box2_value = Integer.valueOf(box2);
                    box3_value = Integer.valueOf(box3);
                    box4_value = Integer.valueOf(box4);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("ThrowVegetables", "解析 json 数据失败");
        }
    }

    private String setType(int box) {
        String text = "";
        switch (box) {
            case 1:
                text = "常规投菜（投两下）";
                break;
            case 2:
                text = "慢速投菜（滞留几秒后归位，不抖动）";
                break;
            case 3:
                text = "快速投菜（投三下）";
                break;
            case 4:
                text = "慢速投菜（投三下）";
                break;
        }
        return text;
    }

    // 辅助方法：更新对应的 TextView
    private void updateTextView(int box, String text,int way) {
        switch (box) {
            case 1:
                textView1.setText(text);
                box1_value = way;
                break;
            case 2:
                textView2.setText(text);
                box2_value = way;
                break;
            case 3:
                textView3.setText(text);
                box3_value = way;
                break;
            case 4:
                textView4.setText(text);
                box4_value = way;
                break;
        }
    }

    // 读取完json数据之后给文本赋值
    public void InitializationText() {
        int[] boxnum = {box1_value, box2_value, box3_value, box4_value};
        for (int i = 0; i < 4; i++) {
            int throwway = boxnum[i];//throwway是第i+1个盒子的投料方式
            updateTextView(i + 1, setType(throwway),throwway);
        }
    }

    // 定义一个方法来处理文本点击事件
    private void textClickListener(int box, int way) {
        String text = "";
        switch (way) {
            case 1:
                text = "常规投菜（投两下）";
                break;
            case 2:
                text = "慢速投菜（滞留几秒后归位，不抖动）";
                break;
            case 3:
                text = "快速投菜（投三下）";
                break;
            case 4:
                text = "慢速投菜（投三下）";
                break;
        }
        // 更新对应的 TextView
        updateTextView(box, text,way);
        // 关闭对话框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    //设置弹窗所选项的方法
    private void setSelect(int box) {
        // 根据当前选中的选项设置对应的 TextView 为选中状态
        int[] BoxValues = new int[]{box1_value, box2_value, box3_value, box4_value};
        TextView[] textViews = new TextView[]{text1, text2, text3, text4};
        ImageView[] imageViews = new ImageView[]{imageView1, imageView2, imageView3, imageView4};
        View[] xianimg = new View[]{xian1,xian2,xian3,xian4};
        int boxIndex = box - 1; // 将 box 转换为 0-based 索引
        int value = BoxValues[boxIndex];
        // 设置选中项的状态
        if (value >= 1 && value <= 4) {
            textViews[value - 1].setSelected(true);
            textViews[value - 1].setTextColor(Color.parseColor("#ff1151E4"));
            imageViews[value - 1].setSelected(true);
            xianimg[value -1].setBackgroundColor(Color.parseColor("#ff1151E4"));
        }
    }
}